angular.module('BaseServer')

.service('BaseExcel', ['BaseFunction', 'BaseEnum', 'BaseService', function(BaseFunction, BaseEnum, BaseService){
    return {
    	Workbook: function(fileName){
            if(fileName == undefined || fileName == null || fileName.trim() == ''){
                fileName = BaseFunction.getGuid().replace(/-/g, '') + ".xlsx";
            }
            else{
                fileName = fileName.split(".")[0] + ".xlsx";
            }

            this.FileName = fileName;       //文件名称
            this.Worksheets = [];           //页签集合
            this.CreatedBy = 'System';            //创建人

            //新增一个页签
            this.addWorksheet = function(sheetName){
            	if(!sheetName){
            		sheetName = 'Sheet' + (this.Worksheets.length + 1).toString();
            	}
            	for(var i=0; i<this.Worksheets.length; i++){
                    if(this.Worksheets[i].Name === sheetName){
                        BaseFunction.alert('添加页签失败：页签名称(' + sheetOrName + ')已经存在', '新增Excel页签出错');
                        return null;
                    }
                }
                var newWorksheet = new Worksheet(sheetName);

                this.Worksheets.push(newWorksheet);
                return newWorksheet;
            };

            //创建Excel
            this.create = function(successHandle, errHandle){
            	BaseService.createExcel(this, successHandle, errHandle);
            };
            //导出Excel
            this.export = function(successHandle, errHandle){
            	this.create(function(excel){
	            	BaseFunction.tip(excel.FileName + '创建完成，正在下载');
                    BaseService.clientDownloadFile(excel.FileName, function(fileName){
                            BaseFunction.tip(fileName + '下载完成');
                            if(successHandle){
                                successHandle(excel);
                            }
                        },
                        errHandle
                    );
                },
                errHandle);
            };

            function Worksheet(sheetName){
                this.Name = sheetName;  //页签显示名称
                this.IsLineNumber = false;	//是否显示行号
	            this.Rows = [];
                this.DataSource = {			//显示数据集合
                	Records: [],			//直接传递数据
                	DataBase: {				//数据库
                		EntityName: null,
                		Condition: null,
                		OrderBy: null,
                		Populate: null
                	}
                };

                //新增一行
                this.addRow = function(isHeaderRow, index){
                	if(isHeaderRow){
                		for(var i=0; i<this.Rows.length; i++){
	            			if(this.Rows[i].IsHeaderRow){
	            				BaseFunction.alert('一个页签最多只能有一个标题行', '程序调用失败');
	            				return null;
	            			}
	            		}
                	}

                    var newRow = new SheetRow(isHeaderRow);

                    if(index){
                        this.Rows.splice(index, 0, newRow);
                    }
                    else{
                        this.Rows.push(newRow);
                    }
                    return newRow;
                };

                //新增一行数据记录
                this.addDataRow = function(rowData, index){
                    if(!rowData){
                        rowData = new Array();
                    }

                    if(index){
                        this.DataSource.Records.splice(index, 0, rowData);
                    }
                    else{
                        this.DataSource.Records.push(rowData);
                    }
                    return rowData;
                };
                
                var worksheet = this;
                function SheetRow(isHeaderRow){
                	this.IsHeaderRow = (isHeaderRow ? isHeaderRow : false);
                	this.Height = null;		//行高度
                    this.Cells = new Array();

                    this.addCell = function(val, index){
                        var newCell = new SheetCell(val);

                        if(index){
                            this.Cells.splice(index, 0, newCell);
                        }
                        else{
                            this.Cells.push(newCell);
                        }
                        return newCell;
                    }

                    if(this.IsHeaderRow){
                    	this.Height = 20;
                    	this.DataRowHeight = null;	//如果是数据列，定义数据行高度
                    	this.IsTotal = false;		//程序自动维护，不允许手动维护
                    }

                    var sheetRow = this;
                    function SheetCell(val){
	                    this.Value = val;
	                    this.MergeCells = null;    //合并单元格
	                    this.Style = {
	                    	font: {
		                        family: 4,
		                        name: '宋体',
		                        size: 10,
		                        color: { argb: '000000' },
		                        underline: false,
		                        bold: false
		                    },
		                    alignment: {
		                        vertical: 'middle',
		                        horizontal: 'left'
		                    },
		                    border: {
		                        top: {style:'thin', color: {argb:'1E93DE'}},
		                        left: {style:'thin', color: {argb:'1E93DE'}},
		                        bottom: {style:'thin', color: {argb:'1E93DE'}},
		                        right: {style:'thin', color: {argb:'1E93DE'}}
		                        //diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}}     //单元格打'X'
		                    },
		                    fill: {
		                        type: 'pattern',
		                        pattern:'solid',
		                        fgColor:{argb:'FFFFFF'},    //背景色
		                        bgColor:{argb:'000000'}
		                    },
		                    numFmt: null
		                };

	                    //如果是数据列，设置数据基本信息，以及单元格样式
	                    if(sheetRow.IsHeaderRow){
	                    	this.Key = '';
		                    this.Width = 11;
		                    this.TotalType = null;
			                this.Round = null;                				//舍入方式，只针对数值、百分比
			                this.DateTimeFormat = null;               		//日期显示格式，只针对日期类型
		                    this.DataCellStyle = {
		                    		font: {
				                        family: 4,
				                        name: '宋体',
				                        size: 10,
				                        color: { argb: '000000' },
				                        underline: false,
				                        bold: false
				                    },
		                    		alignment: {
				                        vertical: 'middle',
				                        horizontal: 'left'
				                    },
				                    border: {
				                        top: {style:'thin', color: {argb:'1E93DE'}},
				                        left: {style:'thin', color: {argb:'1E93DE'}},
				                        bottom: {style:'thin', color: {argb:'1E93DE'}},
				                        right: {style:'thin', color: {argb:'1E93DE'}}
				                        //diagonal: {up: true, down: true, style:'thick', color: {argb:'FFFF0000'}}     //单元格打'X'
				                    },
				                    fill: {
				                        type: 'pattern',
				                        pattern:'solid',
				                        fgColor:{argb:'FFFFFF'},    //背景色
				                        bgColor:{argb:'000000'}
				                    },
		                    		numFmt: null
	                    	};
	                    	this._Enum = null;                         		//绑定的枚举，只针对枚举类型列
	                    	this.__defineGetter__('Enum', function(){
				                return this._Enum;
				            });
	                    	this.__defineSetter__('Enum', function(val){
				                if(this.Type == BaseEnum.ValueType.Enum.Value){
				                	this._Enum = val;
				                	this.DataCellStyle.alignment.horizontal = 'center';
				                }
				            });
	                    	this._Type = BaseEnum.ValueType.String.Value;  		//数据类型，默认为字符串
	                    	this.__defineGetter__('Type', function(){
				                return this._Type;
				            });
	                    	this.__defineSetter__('Type', function(val){
				                this._Type = val;
				                if(val == BaseEnum.ValueType.String.Value){
				                	this.DataCellStyle.alignment.horizontal = 'left';
				                }
				                else if(val == BaseEnum.ValueType.Number.Value){
				                	this.DataCellStyle.alignment.horizontal = 'right';
				                }
				                else if(val == BaseEnum.ValueType.Percent.Value){
				                	this.DataCellStyle.alignment.horizontal = 'right';
				                }
				                else if(val == BaseEnum.ValueType.Boolean.Value){
				                	this.DataCellStyle.alignment.horizontal = 'center';
				                }
				                else if(val == BaseEnum.ValueType.Date.Value){
				                	this.DataCellStyle.alignment.horizontal = 'left';
				                }
				                else if(val == BaseEnum.ValueType.Enum.Value){
				                	this.DataCellStyle.alignment.horizontal = 'center';
				                }
				            });
	                    	this._TotalType = null;                    		//合计类型，只针对数值、百分比列有效，例如：BaseEnum.ValueType.Number.Value
	                    	this.__defineGetter__('TotalType', function(){
				                return this._TotalType;
				            });
	                    	this.__defineSetter__('TotalType', function(val){
	                    		if(this.Type == BaseEnum.ValueType.Number.Value || 
	                    			this.Type == BaseEnum.ValueType.Percent.Value){
					                this._TotalType = val;
					                if(val != null){
					                	sheetRow.IsTotal = true;
					                }
					                else{
					                	if(sheetRow.IsTotal){
					                		sheetRow.IsTotal = false;
					                		for(var i=0; i<sheetRow.Cells.length; i++){
					                			if(sheetRow.Cells[i].TotalType){
					                				sheetRow.IsTotal = true;
					                				break;
					                			}
					                		}
					                	}
					                }
					            }
				            });

	                    	// this.Style.font.size = 11;
				            this.Style.font.bold = true;
				            this.Style.font.color.argb = '1E93DE';
				            this.Style.alignment.horizontal = 'center';
				            this.Style.fill.fgColor.argb = 'EFEFEF';
	                    };
	                };
                };
            };
        },
        getDataGridExcel: function(dataGridScope){
        	var fileName = dataGridScope.ExcelName;
        	if(fileName == ""){
        		fileName = dataGridScope.module.EntityName;
        	}
        	var workbook = new this.Workbook(fileName);

    		if(dataGridScope.IsExport){
                var sheetName = 'Sheet1';
                if(dataGridScope.SheetName != ''){
                	sheetName = dataGridScope.SheetName;
                }
                
                var worksheet = workbook.addWorksheet(sheetName);
                // worksheet.IsLineNumber = true;		//是否显示行号
                //增加标题行
                var headerRow = worksheet.addRow();
                headerRow.Height = 30;
                var headerRowCell = headerRow.addCell(sheetName);
                headerRowCell.Style.fill.fgColor.argb = 'DFDFDF';
                headerRowCell.Style.font.bold = true;
                headerRowCell.Style.font.size = 12;
                headerRowCell.Style.alignment.horizontal = 'center';

                var merageCellLength = dataGridScope.Columns.length;
                if(worksheet.IsLineNumber){
                	merageCellLength++;
                }
                headerRowCell.MergeCells = 'A1:' + this.columnIndexToChar(merageCellLength) + '1';

                //增加数据列行
                var headerRow = worksheet.addRow(true);
                for(var i=0; i<dataGridScope.Columns.length; i++){
                	if(dataGridScope.module.IsEntityModule && dataGridScope.Columns[i].scope.ValueField.indexOf('_') >= 0){
                		continue;
                	}

                    var column = dataGridScope.Columns[i].scope;
                    var rowCell = headerRow.addCell(column.DisplayName);
                    rowCell.Key = column.ValueField;
                    rowCell.Width = parseInt(column.Width.replace('px', '')) / 8;

                    if(column.ControlType == BaseEnum.ControlType.TextBox ||
                        column.ControlType == BaseEnum.ControlType.Refer){
                        rowCell.Type = BaseEnum.ValueType.String.Value;

                        if(column.ControlType == BaseEnum.ControlType.Refer){
                            rowCell.Key += "." + column.TextField;
                        }
                    }
                    else if(column.ControlType == BaseEnum.ControlType.NumberBox){
                        rowCell.Type = BaseEnum.ValueType.Number.Value;
                        rowCell.Round = column.Round;
                        rowCell.TotalType = (column.TotalType ? column.TotalType.Value : null);
                    }
                    else if(column.ControlType == BaseEnum.ControlType.PercentBox){
                        rowCell.Type = BaseEnum.ValueType.Percent.Value;
                        rowCell.Round = column.Round;
                        rowCell.TotalType = (column.TotalType ? column.TotalType.Value : null);
                    }
                    else if(column.ControlType == BaseEnum.ControlType.DropDownList){
                        rowCell.Type = BaseEnum.ValueType.Enum.Value;
                        rowCell.Enum = column.enum;
                    }
                    else if(column.ControlType == BaseEnum.ControlType.Calendar){
                        rowCell.Type = BaseEnum.ValueType.Date.Value;
                        rowCell.DateTimeFormat = column.Type;
                    }
                    else if(column.ControlType == BaseEnum.ControlType.CheckBox){
                        rowCell.Type = BaseEnum.ValueType.Boolean.Value;
                    }
                }

                //数据
                if(dataGridScope.module.IsEntityModule){
                	worksheet.DataSource.DataBase.EntityName = dataGridScope.module.EntityName;
                	worksheet.DataSource.DataBase.Condition = dataGridScope.Condition;
                	worksheet.DataSource.DataBase.OrderBy = dataGridScope.module.OrderBy;
                	worksheet.DataSource.DataBase.Populate = dataGridScope.module.Populate;
                }
                else{
                	worksheet.DataSource.Records = dataGridScope.module.Records;
                }
            }

            return workbook;
        },
        exportDataGridExcel: function(dataGridScope, successHandle, errHandle){
        	var workbook = this.getDataGridExcel(dataGridScope);
        	workbook.export();
        },
        //将数字转换成Excel对应的列号（ABC字符串）
        columnIndexToChar: function(number){
        	var str = '';
            while (number > 0){
                var m = number % 26;
                if (m == 0){
                	m = 26;
                }
                str = String.fromCharCode(m + 64) + str;
                number = (number - m) / 26;
            }
            return str;
        }
 	};
}]);
